<?php
#!/usr/bin/php5-cgi
//ps -ef > test.txt
//top -u root -c
//ID 20523
//telnet 80.179.151.238 9001
//nohup php -q server.php 1>/dev/null/ 2>&1 &
//nohup php -q server.php > log.txt &

$clients = array();
$players = array();
$matrix = array();
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,'80.179.151.238', 9001) or die("Socet Binded!");
socket_listen($socket);
socket_set_nonblock($socket);

while(true)
{
    if(($newc = @socket_accept($socket)) !== false)
    {
		foreach($clients as $key=>$client) {
		 echo "Client $client resourse is: ".get_resource_type($client)."\n";
		 if(get_resource_type($client) == 'Unknown') {
			 unset($clients[$key]);
		 }
		}
        echo "Client $newc has connected\n";
        $clients[] = $newc;
		echo "Total clients: "; var_dump($clients); echo "\n";
		$welcome = "<login>welcome</login>\r\n".chr(0);
		socket_write($newc, $welcome, strlen($welcome));
	}

	$read   = $clients;
	$write  = NULL;
	$except = NULL;
	$num_changed_sockets = @socket_select($read, $write, $except, 0);

	if ($num_changed_sockets === false) {
	   /* Error handling */
	} else if ($num_changed_sockets > 0) {
		foreach ($read as $key=>$client) {
		  if(!socket_last_error($client)) {
			  $data = socket_read($client,512,PHP_BINARY_READ);
			  if($data == '') {
				echo "KILL mother f...".$client."\n";
				socket_shutdown($client, 2);
				socket_close($client);
				clean_clients();
				continue;
			  } else {
				  echo "data read for $client is ok!\n";
				  $buffer[$key].= $data;
			  }
	//		  echo "\n"; var_dump($buffer);
	//		  if(strcmp(str_replace("\n", '', $buffer[$key]), $buffer[$key]) != NULL) {
	//			  $command = str_replace("\n", '', $buffer[$key]);
	//			  $command = str_replace("\r", '', $command);
			if(strcmp(str_replace("^", '', $buffer[$key]), $buffer[$key]) != NULL) {
				$command = str_replace("^", '', $buffer[$key]);
				$buffer[$key] = "";
				echo "\nCommand from client $client: -$command-\n";
//				$command_arr = parseCommand($command);
				$xml = simplexml_load_string($command);
				clientCommand($client, $xml);
			}
		  } else {
			  socket_close($client);
			  clean_clients();
		  }
		}
	}
	if(count($clients) == 2 && count($players) != 2) {
		foreach ($clients as $key=>$client) {
			$players[$key] = array('player'=>0);
		}
		$players_keys = array_keys($players);
		$players[$players_keys[rand(0, 1)]]['player'] = 1;
		foreach ($players as $key=>$player) {
			$data = '<player>'.$player['player'].'</player>'."\r\n".chr(0);
			socket_write($clients[$key], $data, strlen($data));
		}
	}
	sleep(1); //on production change to usleep(2000000); 2 sec.
}

function clean_clients() {
	global $clients, $players, $matrix;
	foreach($clients as $key=>$client) {
	 echo "Client $client resourse is: ".get_resource_type($client)."\n";
	 if(get_resource_type($client) == 'Unknown') {
		 unset($clients[$key]);
	 }
	}
	foreach($clients as $key=>$client) {
		$data = '<disconnected>true</disconnected>'."\r\n".chr(0);
		socket_write($client, $data, strlen($data));
	}
	$players = array();
	$matrix = array();
}

function clientCommand($client, $xml) {
//	var_dump($xml);
//	echo $xml->attributes()->value;
	switch($xml->attributes()->value) {
		case 'cell':
			step($client, $xml);
			break;
		case 'END':
			clientDisconnect($client);
			break;
		case 'KILLme':
			CloseServer();
			break;
		default:
			break;
	}
}

/*
<command value="cell">p2</command>
*/
function step($client, $xml) {
	global $clients, $players, $matrix;

	$key = array_search($client, $clients);
	$place = str_replace('p', '', $xml);

	var_dump($players);echo "\n";
	var_dump($key);echo "\n";
	var_dump($xml);echo "\n";
	echo "place:"; var_dump($place);echo "\n";

	if($matrix[0][$place] == 0) {
		$matrix[0][$place] = 1 + $players[$key]['player'];
		$data = '<step>true</step>'."\r\n".chr(0);
		socket_write($client, $data, strlen($data));
		// get client 2
		$clients_tmp = $clients;
		unset ($clients_tmp[$key]);
		$key = array_keys($clients_tmp);
		$data = '<cell>'.$place.'</cell>'."\r\n".chr(0);
		socket_write($clients_tmp[$key[0]], $data, strlen($data));
	} else {
		$data = '<step>false</step>'."\r\n".chr(0);
		socket_write($client, $data, strlen($data));
	}
	var_dump($matrix);
}

function clientDisconnect($client) {
	echo "\nDisconnect $client.\n";
	socket_shutdown($client, 2);
	socket_close($client);
}

function CloseServer() {
	global $clients;
	
	foreach($clients as $client) {
		socket_shutdown($client, 2);
		@socket_close($client);
	}
	socket_shutdown($socket, 2);
	socket_close($socket);
	
	exit();
}
?>